import React, { useRef, useEffect } from 'react';
import { notification } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
import { connect } from 'dva';
import { Card } from '@/utils/card';
import styles from './style.less';

interface cardBoxProps {
  data: object;
  dispatch: Function;
}

let card;
let loadingControl: any;
const LOADING_KEY = 'LOADINGFONTS';

const CardBox: React.FC<cardBoxProps> = (props: cardBoxProps) => {
  const { data, dispatch } = props;

  const canvas = useRef(null);

  const openNotification = () => {
    loadingControl = setTimeout(() => {
      notification.open({
        key: LOADING_KEY,
        placement: 'topLeft',
        message: '正在加载字体',
        description:
          '中文字体很庞大，请耐心等待哦',
        onClick: () => {
          console.log('Notification Clicked!');
        },
        className: styles.tip,
        duration: null,
        icon: <LoadingOutlined />,
      });
    }, 1000);
  };

  const closeNotification = () => {
    if (loadingControl) {
      clearTimeout(loadingControl);
    }
    notification.close(LOADING_KEY);
  };

  useEffect(() => {
    card = new Card({
      data,
      canvas: canvas.current,
      size: [813, 1185],
      moldPath: './mold',
      fontsLoaded: closeNotification,
    });

    card.render();

    openNotification();

    dispatch({
      type: 'cardData/set-card-ins',
      payload: card,
    });
  }, [canvas])

  return (
    <canvas ref={canvas} />
  );
}

const mapStateToProps = ({ cardData }) => {
  const { data } = cardData;
  return {
    data,
  }
};

export default connect(mapStateToProps)(CardBox);
